<template>
  <el-card shadow="never" class="aui-card--fill">
      <el-form  label-position="top" label-width="100px">

          <el-form-item label="上传毕业设计">
                <file-upload url="/student/paper" @submitToParent="getDataList"></file-upload>
              <!-- <el-upload class="upload-demo" 
                  :ref="file"
                  :show-file-list="true"
                  :auto-upload="true"
                  :headers='token'
                  
                  :with-credentials="true"
                  :drag="true"
                  :action="apiHost"     
                  :on-success="uploadSuccess"
                  :before-upload="beforeUpload"
                  
                  >
                  accept="*"
                  :data="dataForm"
                  :headers='token'
                  :on-remove="handleRemove"
                  :on-exceed="handleExceed"
                  :on-remove="handleRemove"
                  :on-change="changeFile"
                  :on-error="error"
                  :before-remove="beforeRemove"
                  <el-button size="middle" type="primary" icon="el-icon-upload2">上传文件</el-button>
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                  <div slot="tip" class="el-upload__tip">只能上传docx文件,文件大小不超过100M</div>
              </el-upload> -->
          </el-form-item>
      </el-form>

      <!-- "showDatas.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))" -->
      <el-table fixed  :data="tableData" tooltip-effect="dark" 
          @sort-change="sortChange">
          <el-table-column type="index" header-align="center" align="center" label="编号" width="50"></el-table-column>
          <el-table-column prop="filename" header-align="center" align="center"  show-overflow-tooltip label="论文名称"></el-table-column>
          <!-- <el-table-column prop="describes" show-overflow-tooltip label="文献描述" sortable>
          </el-table-column> -->
        <el-table-column prop="status" header-align="center" align="center" show-overflow-tooltip width="120" label="审核状态">
            <template slot-scope="scope">
                <el-tag v-if="scope.row.status === 0" size="small" type="info">审核中</el-tag>
                <el-tag v-if="scope.row.status === 1" size="small" type="danger">驳回</el-tag>
                <el-tag v-if="scope.row.status === 2" size="small" type="success">通过</el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="advise" header-align="center" align="center" width="180" label="指导意见">
        </el-table-column>
          <el-table-column prop="gmtModified" header-align="center" align="center" width="180" label="更改时间">
          </el-table-column>
          <el-table-column fixed="right" header-align="center" align="center" width="290" label="操作">
              <template slot-scope="scope">
                  <!-- <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.userId, scope.row.state,scope.row)">修改
                  </el-button> -->
                    <file-down :pre-view="true" icon="el-icon-check" api-url="/student/down/paper" :file-id="scope.row.id"
                        :FileInfo="scope.row" size="mini" type="success" title="预览"></file-down>
                    <file-down   icon="el-icon-download" api-url="/student/down/paper" :file-id="scope.row.id"
                        :FileInfo="scope.row" size="mini" type="success" title="下载"></file-down>
                  <el-button type="danger" size="mini"   icon="el-icon-delete" @click="deleteHandle(scope.row)">
                      删除</el-button>
                  
                  <!-- <el-button type="success" size="small"  icon="el-icon-download" @click="download(scope.row)">下载</el-button> -->
                
                  
              </template>
          </el-table-column>
      </el-table>

      <!-- <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="tableData.length">
      </el-pagination> -->
  </el-card>
</template>

<script>
import servicesApi from '@/services/servicesApi';
import storageService from '@/store/storage';
import { apiHost } from '@/services/axiosInterceptor';
import FileUpload from '@/components/FileUpload.vue';
import FileDown from '@/components/FileDown.vue';
export default {
    name: 'Table',
    data() {
        return {
            title: '请点击按钮进行下载',
            apiHost: '',
            percentage: 0,
            isDisabled: false,
            fileList: [],
            token: {
                csrftoken: storageService.getToken()
            },
            dataForm: {
                describle: '',
            },
            file: null,
            currentPage: 1,
            pageSize: 10,
            tableData: [],
            showDatas: [], // 展示的table数据
        };
    },
    created() {
        this.getDataList(); // 页面初始化，请求数据并在表格显示
        // this.token.csrftoken=storageService.getToken()
        this.apiHost = apiHost + '/student/paper';
    },
    methods: {
        //删除文献
        deleteHandle(row) {
            this.$confirm(`确定对文件=[${row.filename}]进行[删除操作]?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // this.deleteList.list = userIds
                servicesApi.deleteDFile().then(res => {
                    // console.log(res.data)
                    let code = res.data.code;
                    if (code === 200) {
                        this.$message({
                            message: '删除成功',
                            type: 'success',
                            duration: 500,
                            onClose: () => {
                                this.getDataList();
                            }
                        });
                    }
                    else {
                        this.$message.error(res.data.msg);
                    }
                });
            });
        },
        // 获取数据
        getDataList() {
            this.dataListLoading = true;
            servicesApi.getDesign().then(res => {
                // console.log(res.data)
                let code = res.data.code;
                let data = res.data.data;
                if (code === 200 && data !== null) {
                    let list = [];
                    list[0] = data;
                    this.tableData = list;
                }
                else {
                    this.tableData = [];
                }
                this.dataListLoading = false;
            });
            // this.showDatas = this.tableData.slice(0, this.pageSize);  // 然后显示区间数据（无排序触发），且这里显示1-10条
        },
        //下载文件
        download(row) {
            this.percentage = 0;
            this.percentage = 25;
            // console.log(row)
            let Form = {
                filename: '管理员功能性需求',
                path: 'student/paper',
                suffix: 'docx'
            };
            let FileName = '管理员功能性需求.docx';
            if (row) {
                Form.filename = row.filename;
                Form.path = row.path;
                Form.suffix = row.suffix;
                FileName = Form.filename + '.' + Form.suffix;
            }
            //进度条恢复为 0 
            this.percentage = 50;
            //按钮置灰 不可点击
            this.isDisabled = true;
            servicesApi.downloadFiles(Form).then(res => {
                this.percentage = 75;
                // console.log(res)
                //xml返回数据的钩子函数，可以用来获取数据的进度 具体可查看axios的官网
                //     onDownloadProgress: (progressEvent) => {
                //         //progressEvent.loaded 下载文件的当前大小
                //         //progressEvent.total  下载文件的总大小 如果后端没有返回 请让他加上！
                //         let progressBar = Math.round(progressEvent.loaded / progressEvent.total * 100);
                //         //接收进度为99%的时候需要留一点前端编译的时间
                //         if (progressBar >= 99) {
                this.percentage = 99;
                this.title = '下载完成，文件正在编译。';
                //         } else {
                //             this.percentage = progressBar;
                //             this.title = '正在下载，请稍等。';
                //         }
                //     }
                try {
                    const blob = new Blob([res.data], {
                        type: 'application/octet-stream'
                    });
                    const downloadElement = document.createElement('a');
                    // 创建下载的链接
                    // 兼容不同浏览器的URL对象
                    const url = window.URL || window.webkitURL || window.moxURL;
                    const href = url.createObjectURL(blob);
                    downloadElement.href = href;
                    // 下载后文件名
                    downloadElement.download = FileName;
                    document.body.appendChild(downloadElement);
                    // 点击下载
                    downloadElement.click();
                    // 下载完成移除元素
                    document.body.removeChild(downloadElement);
                    // 释放掉blob对象
                    url.revokeObjectURL(href);
                    //编译文件完成后，进度条展示为100
                    this.percentage = 100;
                    //下载完成 可以重新点击按钮下载
                    this.isDisabled = false;
                }
                catch (error) {
                    // console.log('下载的文件出错', error)
                }
            });
        },
        uploadSuccess(res, file, fileList) {
            // console.log(file)
            // console.log(`======${file.name}文件上传成功=====`)
            if (res.code === 200) {
                this.$message.success('上传成功');
                this.getDataList(); //刷新页面
            }
            else {
                this.$message.error(res.msg);
            }
        },
        changeFile(val) {
            // console.log('选择文件成功');
            this.file = val.raw;
            // console.log(val)
            // console.log(this.file)
            // let nameArray = val.name.split(".");
            // if (nameArray[nameArray.length - 1] === "xlsx") {
            //     // file保存选择的文件
            //     this.file = val.raw;
            // } else {
            //     this.$message({
            //         message: '表格格式错误,请确认表格内容并重新上传',
            //         type: 'warning',
            //         duration: 2000
            //     });
            // }
        },
        submit() {
            // // console.log("提交");
            let myfile = this.$refs.myfile;
            let files = myfile.files;
            this.file = files[0];
            let formData = new FormData();
            formData.append('file', this.file);
            // 添加其他非文件的参数，可以使用set() 方法
            // formData.set('config_type', this.json.config_typ);
            this.loading = true;
            // 接口里面需要指定请求头 headers['Content-Type'] = 'multipart/form-data'
            servicesApi.submitWenxian(formData).then(res => {
                if (res.data.code === 200) {
                    this.$message({
                        message: '操作成功',
                        type: 'success',
                        duration: 500,
                    });
                }
                else {
                    this.$message.error(res.data.msg);
                }
            });
        },
        handleRemove(file, fileList) {
            // console.log(file, fileList);
            return this.$confirm(`确定移除 ${file.name}？`);
        },
        handlePreview(file) {
            // console.log(file);
        },
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },
        //   beforeUpload(file) {
        //       const FileType = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
        //       const isLt20M = file.size / 1024 / 1024 < 20;
        //       if (!FileType) {
        //           this.$message.error('上传文件只能是 docx 格式!');
        //       }
        //       if (!isLt20M) {
        //           this.$message.error('上传文件大小不能超过 20MB!');
        //       }
        //     //   return FileType && isLt20M;
        //       return isLt20M;
        //   },
        beforeUpload(file) {
            // console.log(file)
            const typeList = ['application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
            // const FileType = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
            const size = 100;
            let FileType = false;
            const isLt = file.size / 1024 / 1024 < size;
            if (typeList.includes(file.type)) {
                // console.log('上传文件类型正确')
                FileType = true;
            }
            if (!FileType) {
                this.$message.error('上传文件格式错误!');
            }
            if (!isLt) {
                this.$message.error(`上传文件大小不能超过${size}MB!`);
            }
            return FileType && isLt;
        },
        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${file.name}?`);
        },
        getProgress() {
            //进度条恢复为 0 
            this.percentage = 0;
            //按钮置灰 不可点击
            this.isDisabled = true;
            //发起请求
            servicesApi.downFile()
                // this.$axios({
                //     //下载文件的远端地址。
                //     url: "https://文件地址.html",
                //     //请求方式 get post。   
                //     method: "get",
                //     //设置返回数据类型为base64的数据，这样才可以被new Blob() 解析。    
                //     responseType: "blob",
                //     //请求参数 get-->params   post-->data 。
                //     params: {},
                //     //xml返回数据的钩子函数，可以用来获取数据的进度 具体可查看axios的官网
                //     onDownloadProgress: (progressEvent) => {
                //         //progressEvent.loaded 下载文件的当前大小
                //         //progressEvent.total  下载文件的总大小 如果后端没有返回 请让他加上！
                //         let progressBar = Math.round(progressEvent.loaded / progressEvent.total * 100);
                //         //接收进度为99%的时候需要留一点前端编译的时间
                //         if (progressBar >= 99) {
                //             this.percentage = 99;
                //             this.title = '下载完成，文件正在编译。';
                //         } else {
                //             this.percentage = progressBar;
                //             this.title = '正在下载，请稍等。';
                //         }
                //     }
                // })
                .then(res => {
                //当前定义res.message 出现的时候说明后端文件返回出现了问题 不然应该直接是个文件流 
                if (res.data.code !== 200) {
                    this.title = '下载失败';
                    this.isDisabled = false;
                    return;
                }
                //blob返回的是一个 base64 格式的文件流
                let blob = new Blob([res], {
                    //编译文件为xlsx类型。 具体可查看 blob 方法定义的类型 
                    type: 'application/vnd.ms-excel'
                });
                //编译文件
                if (window.navigator && window.navigator.meSaveOrOpenBlob) {
                    window.navigator.meSaveOrOpenBlob(blob, '文件名称.xlsx');
                }
                else {
                    let Url = window.URL.createObjectURL(blob);
                    let link = document.createElemnet('a');
                    link.style.display = 'none';
                    link.href = Url;
                    link.setAttribute('download', '文件名称.xlsx');
                    document.body.appendChild(link);
                    link.click();
                }
                //编译文件完成后，进度条展示为100
                this.percentage = 100;
                //下载完成 可以重新点击按钮下载
                this.isDisabled = false;
            });
        },
        // 1.改变页面选项触发的方法（val:显示的每页大小）
        handleSizeChange(val) {
            this.currentPage = 1; // 跳转第一页
            this.pageSize = val; // 每页大小赋值给绑定的pageSize
            this.showDatas = this.tableData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize); // 抓取区间数据
        },
        // 2.改变页码触发的方法(val:触发的当前页码)
        handleCurrentChange(val) {
            this.currentPage = val; // 跳转当前页
            this.showDatas = this.tableData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize); // 抓取区间数据
        },
        // 3.排序监听
        sortChange(column) {
            this.tableData = this.tableData.sort(this.SortFun(column.prop, column.order === 'ascending'));
            this.showDatas = this.tableData.slice(0, this.pageSize);
            this.currentPage = 1;
        },
        // 4.排序方法
        SortFun(attr, rev) {
            this.currentPage = 1;
            //第一个参数传入info里的prop表示排的是哪一列，第二个参数是升还是降排序
            if (rev == undefined) {
                rev = 1;
            }
            else {
                rev = rev ? 1 : -1;
                //rev = rev>0 ? 1 : -1;
            }
            return function(a, b) {
                a = a[attr];
                b = b[attr];
                if (a != null) {
                    // 1.列数据类型为string时的排序
                    if (typeof a == 'string') {
                        // 1.1 判断是否为日期类型
                        if (a.split(' ').length === 2) {
                            if (a < b) {
                                return rev * -1;
                            }
                            if (a > b) {
                                return rev * 1;
                            }
                            return 0;
                        }
                        else if (!isNaN(a)) {
                            // 是否能转为数字类型
                            // // console.log("字符数字类型",attr,a)
                            if (parseFloat(a) < parseFloat(b)) {
                                return rev * -1;
                            }
                            if (a > b) {
                                return rev * 1;
                            }
                            return 0;
                        }
                        else {
                            // 1.2 普通字符类型
                            //// console.log("普通字符类型",attr,a)
                            if (a < b) {
                                return rev * -1;
                            }
                            if (a > b) {
                                return rev * 1;
                            }
                            return 0;
                        }
                    }
                    // 2. 列数据类型为number时的排序
                    if (typeof a == 'number') {
                        //// console.log("Number型:", a);
                        if (a < b) {
                            return rev * -1;
                        }
                        if (a > b) {
                            return rev * 1;
                        }
                        return 0;
                    }
                }
            };
        },
    },
    components: { FileUpload, FileDown }
};
</script>

<style scoped>
</style>
